<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,initial-scale=1.0,width=device-width" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>任务列表</title>
    <!-- 基本框架 -->
    <link rel="stylesheet" href="../../../css/common.css">
    <script src="../../../script/vue.min.js" type="text/javascript"></script>
    <script src="../../../script/frame.js" type="text/javascript"></script>
    <script src="../../../script/baseConfig.js" type="text/javascript"></script>
    <script src="../../../script/utils.js" type="text/javascript"></script>
    <script src="../../../script/common.js" type="text/javascript"></script>
    <style>
        #container {
            padding: 0;
        }

        .myTaskList {}

        .myTaskList li {
            background: #FFF;
            padding: 0.6rem 0.35rem;
            padding-bottom: 0;
            margin-top: 0.15rem;
            position: relative;
        }

        .myTaskList li .import {
            padding-bottom: 0.5rem;
            position: relative;
        }

        .myTaskList li .import .icon {
            width: 1.2rem;
            height: 1.2rem;
            border-radius: 50%;
            float: left;
        }

        .myTaskList li .import .info {
            padding-left: 0.4rem;
            float: left;
            width: calc(100% - 1.2rem);
        }

        .myTaskList li .import .info h3 {
            font-weight: normal;
            color: #464646;
            font-size: 0.3rem;
            height: 0.4rem;
            line-height: 0.4rem;
        }

        .myTaskList li .import .info .price {
            margin-top: 0.28rem;
        }

        .myTaskList li .import .info .price .left {
            color: #F30;
            font-size: 0.35rem;
            font-weight: bold;
            height: 0.65rem;
            line-height: 0.65rem;
        }

        .myTaskList li .import .info .price .right {
            padding: 0px 0.3rem;
            color: #a9a9a9;
            border: 1px solid #F6F6F6;
            border-radius: 0.05rem;
            height: 0.65rem;
            line-height: calc(0.65rem - 2px);
            display: block;
            font-size: 0.27rem;
        }
        .info .rtMore{
            padding: 0.1rem 0.52rem;
            border: 1px solid #F6F6F6;
            font-size: 0.27rem;
            color: #333333;
            border-radius: .24rem;
            display: flex;
            align-items: center;
            cursor: pointer;
        }
        .personIcon{
            height: .25rem!important;
            width: auto!important;
        }
        .statusDiv.flex {
            display: flex;
            justify-content: space-between;
        }

        .statusDiv {
            border-top: 1px solid #F9F9F9;
        }

        .statusDiv .left {
            height: 0.95rem;
            line-height: 0.95rem;
            font-size: 0.28rem;
            color: #9F9F9F;
            padding-right: 0.2rem;
        }

        .statusDiv .left img {
            vertical-align: middle;
            margin-top: -0.05rem;
            margin-right: 0.15rem;
            width: 0.3rem;
            height: 0.3rem;
        }

        .statusDiv .right {
            height: 0.95rem;
            line-height: 0.95rem;
            font-size: 0.28rem;
            color: #B1B1B1;
        }

        .lookArb {
            position: absolute;
            right: 0rem;
            top: 0rem;
            background: url('../../../image/task/lookarb.png')no-repeat center center;
            background-size: 100% 100%;
            width: 0.7rem;
            height: 0.7rem;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
		<div class="loadFull whiteBg" v-if="blocked">
			<div class="blocked">
			    <img src="../../../image/public/blocked.png">
			    请先登录您的账号，现在<font @click="$.openUrl('common/commonUser','common/login');">登录</font>
			</div>
		</div>
        <div id="container" v-else>
            <template v-if="isPageLoading">
                <div class="loadFull whiteBg pageload">
                    <div class="se-loading"></div>
                </div>
            </template>
            <template v-else>
				<template v-if="hasData">
				    <ul class="myTaskList">
				        <template
				            v-if="type == 0"
				        >
				                <single-accept
				                    v-for="(acceptItem,acceptIndex) of acceptList"
				                    :key="acceptItem.id"
				                    :single-accept="acceptItem"
				                    @giveuptask="giveUpTask(acceptIndex)"
				                    @navtaskdetail="navTaskDetail(acceptItem.task.id,acceptItem.id)"
				                />
				        </template>
				        <template
				            v-if="type == 1"
				        >
				            <single-send
				                v-for="(sendItem,sendIndex) of sendList"
				                :key="sendItem.id"
				                :single-send="sendItem"
				            />
				        </template>
				    <ul>
				</template>
				<template v-if="hasData">
					<div class="loadText">
						<div class="weui-loadmore"
							v-if="infiniteLoad"
						>
							<i class="weui-loading"></i>
							<span class="weui-loadmore__tips">正在加载</span>
						</div>
						<span class="over" v-if="!allowInfinite">我已经到底啦！</span>
					</div>
				</template>
				<template
				    v-if="!hasData"
				>
				    <div class="loadFull whiteBg">
				        <section class="m-no">
				            <div class="u-img"></div>
				            <div class="u-spec">暂无数据</div>
				        </section>
				    </div>
				</template>
			</template>
        </div>
    </div>
    <script type="text/javascript">
        Vue.component('single-accept', {
            props: ['singleAccept'],
            created() {
            },
            template: `
                <li
                    @click="navTaskDetail"
                >
                    <div class="import clearfix"
                    >
                        <img :src="singleAccept.platform.icon.url" class="icon" />
                        <div class="info">
                            <h3 class="ell">{{singleAccept.task.title}}</h3>
                            <div class="price disbox" >
                                <div class="left disflex ell">
                                    +{{Number(singleAccept.amount/10000).toFixed(2)}}
                                </div>
                                <a class="right"
                                    v-if="singleAccept.status.value == 1"
                                    @click.stop
                                    @click="giveUpTask"
                                >
                                    放弃任务
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="statusDiv disbox flex">
                        <div>
                            <div class="left disflex ell flexItemCenter" v-if="singleAccept.status.value == 2">
                                <img src="../../../image/icons/time.png" />
                                <font>
                                    {{singleAccept.time_auto_approved | dateFormate}} 前审核完成
                                </font>
                            </div>
                            <div class="left disflex ell flexItemCenter" v-else>
                                <img src="../../../image/icons/time.png" />
                                <font>
                                    {{singleAccept.dateText}}
                                </font>
                                {{disStatusLHint(singleAccept.status.value)}}
                            </div>
                        </div>
                        <div>
                            <div class="right" :style="{color:getStatusColor(singleAccept.status.value)}">
                                {{singleAccept.status.text}}
                            </div>
                        </div>
                    </div>
                    <font @click.stop="goArbitrationDetail(singleAccept.arbitration_id)" class="lookArb"
                        v-if="singleAccept.status.value == 4"
                    ></font>
                </li>
            `,
            filters: {
                dateFormate: function(time){
                    return utils.tsToDateFormat(time, 'M-d hh:mm');
                },
            },
            methods: {
                getStatusColor: function(status){
                    // 
                    var colors = {
                        gray: '#b8b8b8',
                        green: '#67d765',
                        red: '#ff4e4e',
                        blue: '#719dff',
                    };
                    var statusColors = {
                        1: colors.gray,
                        2: colors.gray,
                        3: colors.green,
                        4: colors.blue,
                        5: colors.red,
                        6: colors.red,
                    };
                    return statusColors[~~status];
                },
                disStatusLHint(status) {
                    if (status == 1) {
                        return '内完成任务';
                    }
                    if (status == 2) {
                        return '提交了该任务';
                    }
                    if (status == 3) {
                        return '完成了该任务';
                    }
                    if (status == 5) {
                        return '被判定未通过';
                    }
                    return '关闭了该任务'
                },
                giveUpTask() {
                    this.$emit('giveuptask');
                },
                navTaskDetail: function () {
                    this.$emit('navtaskdetail');
                },
                goArbitrationDetail: function(aid){
                    $.openUrl('my/newArbitrationDetail','my/newArbitrationDetail',{title:'仲裁详情', id: aid});
                },
            }
        });
        Vue.component('single-send', {
            props: ['singleSend'],
            template: `
                <li
                    @click="navTaskPublishDetail(singleSend.id)"
                >
                        <div  class="import clearfix">
                        <img :src="singleSend.platform.icon.url" class="icon" />
                        <div class="info">
                            <h3 class="ell">{{singleSend.title}}</h3>
                            <div class="price disbox">
                            <div class="left disflex ell">
                                <font style="font-size:0.28rem;font-weight:normal;">总价：</font>
                                {{Number((singleSend.amount_total * ((100 - singleSend.amount_platform_ratio) / 100)) / 10000).toFixed(2)}}
                                </div>
                                <div @click.stop="doMore" class="rtMore"
                                    v-if="singleSend.status.value == 2"
                                >更多</div>
                            </div>
                        </div>
                        </div>
                        <div class="statusDiv disbox">
                        <div class="left disflex ell">
                            <img src="../../../image/icons/person.png" class="personIcon" />
                            任务进度：
                            <font color="#F30">
                                {{singleSend.total_accepts-singleSend.total_surplus_accepts}}
                                </font>/{{singleSend.total_accepts}}
                        </div>
                        <div class="right" :style="{color: getStatusColor(singleSend.status.value)}">{{singleSend.status.text}}</div>
                        </div>
                </li>
            `,
            methods: {
                getStatusColor: function(status){
                    // 
                    var colors = {
                        gray: '#b8b8b8',
                        green: '#67d765',
                        red: '#ff4e4e',
                        blue: '#719dff',
                    };
                    var statusColors = {
                        1: colors.gray,
                        2: colors.gray,
                        3: colors.green,
                        4: colors.red,
                        5: colors.red,
                        6: colors.gray,
                    };
                    return statusColors[~~status];
                },
                navTaskPublishDetail(taskId){
                    $.openUrl('common/commonTitle','task/sendDetail',{title:'派单详情',taskId: taskId});
                },
                doMore: function(id){
                    var _this = this;
                    var is_top = this.singleSend.is_top;
                    var firstItemName = is_top == 0 ? '置顶' : '加时置顶';
                    
                    var param = {title:"更多操作",items:[firstItemName,"提前结束"]};
                    var iOSDialog = api.require('iOSDialog');

                    iOSDialog.actionSheetDialog(param,function(ret, err){
                        if(ret.index == 1){
                            _this.setTop();
                        }else if(ret.index == 2){
                            _this.releaseTask();
                        }
                    });
                },
                setTop: function(){
                    var id = this.singleSend.id;
                    var is_top = this.singleSend.is_top;
                    var _this = this;

                    $.ajax({
                        url: '/task/top/index',
                        method: 'get',
                        success: function(res){
                            var count = res.data.count;
                            var unit = $.parsePrice(res.data.topHourFee, 2);
                            if(is_top == 0 && count <= 0){
                                $.toast('置顶名额已满');
                                return false;
                            }
                            var actionName = is_top == 0 ? '置顶' : '加时置顶'
                            $.prompt({
                                title: actionName,
                                msg: '请输入'+actionName+'时长，单位：小时，价格：'+unit+'元/小时',
                                text: '1',
                                type: 'number',
                                buttons: ['取消','确定'],
                                success: function(hour){
                                    $.ajax({
                                        url: '/task/top/index',
                                        method: 'post',
                                        load: true,
                                        data: {
                                            task_id: id,
                                            hour: hour,
                                            is_add: is_top
                                        },
                                        success: function(res){
                                            $.toast('置顶成功');
                                            _this.$set(_this.singleSend, 'is_top', 1)
                                        }
                                    });
                                },
                            });
                        }
                    });

                    
                },
                releaseTask: function(id){
                    var _this = this;
                    $.ajax({
                        url: '/get/config?key=taskRefundRate',
                        method: 'get',
                        success: function(res){
                            var msg = '提前结束会将未完成的任务赏金扣除'+res.data.taskRefundRate+'%手续费后返还到您的余额，确定？';
                            $.confirm({
                                msg: msg,
                                buttons: ['取消','确定'],
                                success: function(ret, err){
                                    $.ajax({
                                        url: '/task/refund/my',
                                        method: 'post',
                                        load: true,
                                        data: {ta_id: _this.singleSend.id},
                                        success: function(res){
                                            $.toast('进入清算流程，请等待到账');
                                            api.sendEvent({name: 'updatePublishTaskList'});
                                        },
                                    });
                                }
                            });
                        },
                    });
                    
                    
                },
            },
        })
        apiready = function() {
            var app = new Vue({
                el: '#app',
                data: {
					iosTest:false,
					isDown:false,
					ajaxLoad:false,
                    // 接单列表
                    acceptList: [],
                    // 派单列表
                    sendList: [],
                    // 属性 0 接单 1 派单
                    type: 0,
                    // 状态
                    status: '',
                    page: 1,
                    allowInfinite: false,
                    infiniteLoad: false,
                    isPageLoading: true,
                    pageTimer: null,

					first:true,//是否首次加载,默认是
					blocked:false,
                },
                mounted() {
					$.initJs(this);
                    clearInterval(this.pageTimer);
                },
                destroyed() {
                    clearInterval(this.pageTimer);
                },
                computed: {
                    hasData() {
                        if (this.type == 0) {
                            return this.acceptList[0];
                        }
                        if (this.type == 1) {
                            return this.sendList[0];
                        }
                    }
                },
                methods: {
                    refeshByPar(type,status) {
						var _this = this;
						if(!_this.first){
							return;//切换页面每次触发这个事件以后,先判断是否第一次加载,如果不是就不用重复加载了.
						}

						if(!$.isLogin()){
							_this.blocked = true;
							return;
						}else{
							_this.blocked = false;
							if(_this.isDown==false){
								_this.isDown = true;
								//下拉刷新
								console.log("初始化下拉");
								$.pullDown({
								    success: function() {
								        _this.refresh();
								    }
								});
							}
						}
                        _this.page = 1;
						_this.first = false;
                        _this.type = type;
                        _this.status = status;
                        _this.isPageLoading = true;
						_this.acceptList = [];
						_this.sendList = [];
                        if (type == 0) {
                            _this.fetchAcceptListApi({
                                status
                            },'new');
                            return;
                        }
                        if (type == 1) {
                            _this.fetchSendListApi({
                                status
                            },'new');
							return;
                        }
                    },
                    refresh() {
						var _this = this;
                        this.allowInfinite =  false,
                        this.infiniteLoad = false,
                        this.blocked = false;
                        this.isPageLoading = false;
						if(!$.isLogin()){
							_this.blocked = true;
							api.refreshHeaderLoadDone();
							return;
						}else{
							_this.blocked = false;
						}

                        this.page = 1;
                        if (this.type == 0) {
                            this.fetchAcceptListApi({
                                status: this.status
                            },'new');
                            return;
                        }
                        if (this.type == 1) {
                            this.fetchSendListApi({
                                status: this.status
                            },'new');
                        }
                    },
                    loadMore() {
                        if (!this.allowInfinite) {
                            return;
                        }
                        this.infiniteLoad = true;
						
						if (this.type == 0) {
							this.fetchAcceptListApi({
							    page: this.page,
							    status: this.status
							});
						}
						if (this.type == 1) {
							this.fetchSendListApi({
								page: this.page,
							    status: this.status
							});
						}
                    }, 
                    fetchAcceptListApi({page=1,status=''},hdType) {
                        let _self = this;
						if(_self.ajaxLoad){
							return;
						}else{
							_self.ajaxLoad = true;
							console.log("接单列表接口请求" + page);
						}
						clearInterval(this.pageTimer);
                        $.comRequest('get','/task/accept/my',{
                            page,
                            status
                        },(res)=>{
							_self.ajaxLoad = false;
							_self.blocked = false;
                            _self.isPageLoading = false;
                            _self.infiniteLoad = false;
                            _self.allowInfinite = false;
                            let { records,total_records,page,limit } = res.data;
                            if ( total_records > page*limit ) {
                                _self.allowInfinite = true;
                                _self.page = _self.page + 1;
                            }
                            if (hdType === 'new') {
                                _self.acceptList = [];
                                _self.parseList(records)
                                api.sendEvent({
                                    name: 'taskNums',
                                    extra: {
                                        nums: total_records
                                    }
                                });
                            }else{
                                _self.parseList(_self.acceptList.concat(records))
                            }
                            api.sendEvent({name: 'updatedByTabNav'});
                        },(ero)=>{
							if(ero.code==401){
								_self.blocked = true;
								_self.first = true;
							}
							_self.ajaxLoad = false;
                            _self.isPageLoading = false;
                            _self.infiniteLoad = false;
                            _self.allowInfinite = false;
                            if (hdType === 'new') {
                                _self.acceptList = [];
                                api.sendEvent({
                                    name: 'taskNums',
                                    extra: {
                                        nums: 0
                                    }
                                });
                            }
                            api.sendEvent({name: 'updatedByTabNav'});
                        });
                    }, 
                    giveUpTask(taskIndex) {
                        let curTask = this.acceptList[taskIndex];
                        this.giveUpTaskApi(curTask.id,taskIndex);
                    },
                    giveUpTaskApi(taskId,taskIndex) {
                        let _self = this;
                        let acceptList = JSON.parse(JSON.stringify(_self.acceptList));
                        $.confirm({
                            title: '提示',
                            msg: '确定放弃该任务?',
                            buttons: ['取消','确定'],
                            success:function(){
                                $.comRequest('post','/task/accept/release',{ta_id: taskId},()=>{
                                    clearInterval(_self.pageTimer);
                                    acceptList[taskIndex].status = {
                                        tag: "Closed",
                                        text: "已关闭",
                                        value: 6
                                    };
                                    _self.parseList(acceptList);
									
                                    api.sendEvent({
                                        name:'updateHomeTaskItemIsAbleAccept', 
                                        extra: {
                                            taskId: acceptList[taskIndex].task.id,
                                            isAbleAccept: 1
                                        }
                                    });
                                    $.toast('放弃任务成功');
                                },(ero)=>{
                                    $.toast(ero.message);
                                });
                            }
                        });
                    },
                    fetchSendListApi({page=1,status=''},hdType) {
                        let _self = this;
                        if(_self.ajaxLoad){
                        	return;
                        }else{
                        	_self.ajaxLoad = true;
							console.log("派单列表接口请求" + page);
                        }
                        clearInterval(this.pageTimer);
                        $.comRequest('get','/task/my',{
                            page,
                            status
                        },(res)=>{
							_self.ajaxLoad = false;
                            _self.isPageLoading = false;
                            _self.infiniteLoad = false;
                            _self.allowInfinite = false;
                            let { records,total_records,page,limit } = res.data;
                            if (page==1) {
                                _self.sendList = [];
                                _self.sendList = records;
                                api.sendEvent({
                                    name: 'taskNums',
                                    extra: {
                                        nums: total_records
                                    }
                                });
                            }else{
                                _self.sendList = _self.sendList.concat(records)
                            }
							
							if ( total_records > page*limit ) {
							    _self.allowInfinite = true;
							    _self.page ++;
							}
                        },(ero)=>{
							_self.ajaxLoad = false;
                            _self.isPageLoading = false;
                            _self.infiniteLoad = false;
                            _self.allowInfinite = false;
                            if (hdType === 'new') {
                                _self.sendList = [];
                                api.sendEvent({
                                    name: 'taskNums',
                                    extra: {
                                        nums: 0
                                    }
                                });
                            }
                            api.sendEvent({name: 'updatedByTabNav'});
                        });
                    },
                    parseList(list) {
                        let isOpenTiemr = false;
                        for (let index=0;index<list.length;index++) {
                            let curTask = list[index];
                            let dateText= '';
                            // 任务进行中
                            if (curTask.status.value == 1) {
                                isOpenTiemr = true;
                                dateText = countDown(curTask.time_auto_release).text;
                            }else{
                                let dateObj = utils.getFormatDate(curTask.status_time);
                                dateText= `${dateObj.month}-${dateObj.day} ${dateObj.hour}:${dateObj.minutes}`;
                            }
                            curTask.dateText = dateText;
                        }
                        this.acceptList = list;
                        if (isOpenTiemr) {
                            this.taskCommitTimer();
                        }
                    },
                    taskCommitTimer() {
                        let _self = this;
                        this.pageTimer = setInterval(()=>{
                            let acceptList = _self.acceptList;
                            let closeTimer = true;
                            for (let index=0;index<acceptList.length;index++) {
                                let curTask = acceptList[index];
                                // 任务进行中
                                if (curTask.status.value == 1) {
                                    let date = countDown(curTask.time_auto_release);
                                    if (!date.isEnd) {
                                        closeTimer = false;
                                    }
                                    curTask.dateText = date.text;
                                    _self.$set(_self.acceptList,index,curTask);
                                }
                            }
                            if (closeTimer) {
                                clearInterval(_self.pageTimer);
                            }
                        },998);
                    },
                    navTaskDetail(taskId,acceptId) {
                        $.openUrl('common/commonTitle','task/detail',{title:'任务详情',topShare: true, taskId: taskId,acceptId: acceptId});
                    }
                },
            });
            /**
             * 倒计时
             * @param   {[String]}  endTime    结束时间
             */
            function countDown(endTime){
                let that = this ;
                // 任务自动释放毫秒数
                endTime = endTime*1000;
                // 现在时间毫秒数
                let now = new Date().getTime();
                // 剩余秒数
                let result = (endTime-now)/1000;
                if(result<=0){
                    return {
                        isEnd: true,
                        text: "00:00:00"
                    };
                }else{
                    let h = parseInt(result/60/60);
                    let m = parseInt(result/60%60);
                    let s = parseInt(result%60);
                    h = h < 10 ? ('0' + h) : h;
                    m = m < 10 ? ('0' + m) : m;
                    s = s < 10 ? ('0' + s) : s;
                    return {
                        isEnd: false,
                        text:`请在 ${h}:${m}:${s}`
                    };
                }
            }

			//请求网络
			api.addEventListener({
				name: 'navGetData'
			}, function(ret, err){
				//触发条件有两个：1.首次进本页面   2.mustGet必须请求
				if((ret && app.first && ret.value.navIndex == 1) || (ret.value.navIndex==1 && ret.value.mustGet)){
					app.first = true;
					app.refeshByPar(ret.value.type,ret.value.status);
				}
			});

            // 上拉加载
            api.addEventListener({
            　　name:'scrolltobottom',
                extra:{threshold:0}
            }, function(ret, err){
                app.loadMore();
            });

			api.addEventListener({
			　　name:'loginSuccess',
			    extra:{threshold:0}
			}, function(ret, err){
			    app.first = true;
			});

			api.addEventListener({
			　　name:'loginExit',
			    extra:{threshold:0}
			}, function(ret, err){
				app.first = true;
			    app.blocked = true;
            });
            
            
            api.addEventListener({
                name: 'updatePublishTaskList'
            }, function(ret, err){
                app.refresh();
            });
			
			api.sendEvent({name: 'navInitSuccess'});
        }
    </script>
</body>

</html>
